class_name TopdownMovementControl extends Node2D
##持有这个组件的单位
@export var owner_unit : Unit
##组件类型
@export var component_type_list : Array[Enums.COMPONENT_TYPE] = [Enums.COMPONENT_TYPE.MOVEMENT_CONTROL]
#面向处理方式
@export var face_to_process_type : Enums.FACE_TO_PROCESS_TYPE = Enums.FACE_TO_PROCESS_TYPE.NONE_PROCESS
##移动动画
@export var body_animation_move : String
##停止动画
@export var body_animation_idle : String
##是否启用
@export var enable : bool = true
##单位属性
@export var unit_attribute : Attribute
#玩家动画播放器
@export var body_animation_player : AnimationPlayer
##移动代理
@export var movement_proxy : Node2D
#当前是否正在进行输入
var is_in_control : bool = false

func _unit_ready():
	if !unit_attribute:
		unit_attribute = owner_unit.get_first_component_by_type(Enums.COMPONENT_TYPE.ATTRIBUTE)
	assert(unit_attribute, "unit must have Attribute component")
	if !movement_proxy:
		movement_proxy = owner_unit.get_first_component_by_type(Enums.COMPONENT_TYPE.MOVEMENT_PROXY)
	assert(movement_proxy, "unit must have MovementProxy component")
	assert("move_velocity" in movement_proxy, "MovementProxy must have move_velocity property")

func _process(delta: float) -> void:
	if !enable:
		return
	var input = _process_movement_control(delta)
	_process_face_to(input)
	_process_animation()

#处理移动(返回四个方向的输入值)
func _process_movement_control(delta: float) -> Vector2:
	var input = Vector2(Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left"), Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up"))
	if input.length() > 0:
		is_in_control = true
		movement_proxy.move_velocity = movement_proxy.move_velocity + unit_attribute.max_steering_force * input.normalized()
	else:
		is_in_control = false
		if movement_proxy.move_velocity.length() > 1:
			movement_proxy.move_velocity = lerp(movement_proxy.move_velocity, Vector2.ZERO, unit_attribute.friction)
		else:
			movement_proxy.move_velocity = Vector2.ZERO
	return input

#处理面向
func _process_face_to(input : Vector2):
	if face_to_process_type == Enums.FACE_TO_PROCESS_TYPE.NONE_PROCESS:
		return
	elif face_to_process_type == Enums.FACE_TO_PROCESS_TYPE.MOUSE_DIRECT:
		var mouse_diff = get_global_mouse_position() - global_position
		if mouse_diff.x < 0:
			owner_unit.body_position.scale = Vector2(-1, 1)
		elif mouse_diff.x > 0:
			owner_unit.body_position.scale = Vector2(1, 1)
	else:
		if input.x < 0:
			owner_unit.body_position.scale = Vector2(-1, 1)
		elif input.x > 0:
			owner_unit.body_position.scale = Vector2(1, 1)
#处理动画
func _process_animation():
	if body_animation_player && is_in_control && body_animation_move != null:
		body_animation_player.play(body_animation_move)
	elif body_animation_player && !is_in_control && body_animation_idle != null:
		body_animation_player.play(body_animation_idle)
